package com.breeze.blockchain.service;

import static com.breeze.blockchain.common.exception.BizErrorCode.USER_NOT_FOUND_ERROR;

import com.breeze.blockchain.mybatis.entity.UserDo;
import com.breeze.components.core.exception.ApiException;
import com.breeze.components.core.util.web.RequestContextUtil;
import com.mybatisflex.core.service.IService;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 用户信息表 服务层。
 *
 * @author breeze
 * @since 2024-04-21 20:47:54
 */
public interface UserService extends IService<UserDo> {

  default UserDo getExistsUserByMobile(String mobile) {
    return getUserOptByMobile(mobile).orElseThrow(() -> new ApiException(USER_NOT_FOUND_ERROR));
  }

  default UserDo getNormalStatusUserByMobile(String mobile) {
    UserDo user = getExistsUserByMobile(mobile);
    user.statusCheck();
    return user;
  }

  default Optional<UserDo> getUserOptByMobile(String mobile) {
    return queryChain().eq(UserDo::getMobile, mobile).oneOpt();
  }

  default void updateLastLoginInfo(Long userId) {
    updateChain()
        .eq(UserDo::getId, userId)
        .set(UserDo::getLastLoginTime, LocalDateTime.now())
        .set(UserDo::getLastLoginIp, RequestContextUtil.getClientIp())
        .update();
  }
}
